package com.gzj.environment.module.collectData.message.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.gzj.environment.constant.CollectDataConstant;
import com.gzj.environment.enums.collectData.CollectDataTypeEnum;
import com.gzj.environment.module.collectData.context.ClientContext;
import com.gzj.environment.module.collectData.indicator.IndicatorHandle;
import com.gzj.environment.module.collectData.message.Message;
import io.netty.channel.ChannelHandlerContext;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@NoArgsConstructor
public class IndicatorMessage implements Message {

    private final Map<CollectDataTypeEnum, IndicatorHandle> indicatorHandleMap = new ConcurrentHashMap<>();

    @Autowired
    public IndicatorMessage(List<IndicatorHandle> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            for (IndicatorHandle handle : list) {
                indicatorHandleMap.put(handle.indicatorType(), handle);
            }
        }
    }

    /**
     * 消息类型
     *
     * @return
     */
    @Override
    public String messageType() {
        return CollectDataConstant.MESSAGE_TYPE_IS_INDICATOR;
    }

    /**
     * 处理消息
     * @param ctx netty客户端通道信息
     * @param message 消息内容
     */
    @Override
    public void handle(ChannelHandlerContext ctx, String message) {
        log.info("处理ip为{}的指标消息，消息内容为{}", ctx.channel().remoteAddress(), message);
        // 根据ctx获取它的客户端类型和点位组
        Map<String, String> infoMap = ClientContext.findChannelInfoForContext(ctx);
        String type = infoMap.get("type");
        String group = infoMap.get("group");
        String number = infoMap.get("number");

        indicatorHandleMap.get(getNameForType(type)).indicatorHandle(group, number, ctx, message);
    }

    public CollectDataTypeEnum getNameForType(String type) {
        if (type.equals("1")) {
            return CollectDataTypeEnum.AIR;
        }
        return null;
    }
}
